package com.xbn.xbnmall.ware.service.impl;

import com.xbn.common.constant.WareConstant;
import com.xbn.xbnmall.ware.entity.PurchaseDetailEntity;
import com.xbn.xbnmall.ware.service.PurchaseDetailService;
import com.xbn.xbnmall.ware.service.WareSkuService;
import com.xbn.xbnmall.ware.vo.MergeVo;
import com.xbn.xbnmall.ware.vo.PurchaseFinishVo;
import com.xbn.xbnmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbn.common.utils.PageUtils;
import com.xbn.common.utils.Query;

import com.xbn.xbnmall.ware.dao.PurchaseDao;
import com.xbn.xbnmall.ware.entity.PurchaseEntity;
import com.xbn.xbnmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService detailService;
    @Autowired
    private PurchaseDao purchaseDao;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }
    /*
     * 查询没有被领取的采购单
     * */
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().eq("status",0)
                .or().eq("status",1)
        );

        return new PageUtils(page);

    }
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchasedId = mergeVo.getPurchaseId();
        if(purchasedId==null)
        {
            //如果参数中没有采购单，也就是前端没有选择任何合并的采购单，那么新增一个
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setPriority(1);
            purchaseEntity.setStatus(WareConstant.PurchaseEnum.CREATED.getCode());
            this.save(purchaseEntity);

            purchasedId=purchaseEntity.getId();
        }



        List<Long> items = mergeVo.getItems();
        Long finalPurchasedId = purchasedId;
        List<PurchaseDetailEntity> collect = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchasedId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        })
     /*           .filter(item->{
            //只有新建状态的采购需求才可以被合并分配
            if(item.getStatus()==WareConstant.PurchaseDetailEnum.CREATED.getCode())
            {
                return true;
            }
            else {
                return false;
            }
        })*/
                .collect(Collectors.toList());
        detailService.updateBatchById(collect);
        PurchaseEntity updateTime = new PurchaseEntity();
        updateTime.setId(purchasedId);
        updateTime.setUpdateTime(new Date());
        this.updateById(updateTime);
    }

    /*
    * 领取采购单，修改相关采购单以及采购单下的所有采购采购需求的状态
    * */
    @Override
    public void received(List<Long> ids) {
        //1、确认当前采购单是新建或者已经分配状态，只有这两种采购单可以被领取
        //2、还必须是自己的采购单才可以领取，不能领取分配给别人的采购单
        //3、改变采购项目的状态
        //先查询出所有选中需要被领取的采购单
        List<PurchaseEntity> purchaseEntities = purchaseDao.selectBatchIds(ids);
        //过滤所有状态码不是新建或者已分配状态的采购 需求
        List<PurchaseEntity> collect = purchaseEntities.stream().filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.PurchaseEnum.ASSIGNED.getCode()) {
                return true;
            }
            return false;
        })
                //过滤完成之后，重新给这些采购项设置最新的状态
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseEnum.RECEIVE.getCode());
                    return item;
                })
                .collect(Collectors.toList());
        if(collect!=null&&collect.size()>0) {
            this.updateBatchById(collect);
            //以上是修改采购单的状态，接下来要修改采购单下采购项的状态
            collect.forEach((item) -> {
                List<PurchaseDetailEntity> detailEntities = detailService.listDetailByPurchaseId(item.getId());
                List<PurchaseDetailEntity> updateDetails = detailEntities.stream().map(detail -> {
                    PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                    purchaseDetailEntity.setId(detail.getId());
                    purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailEnum.BUYING.getCode());
                    return purchaseDetailEntity;
                }).collect(Collectors.toList());
                detailService.updateBatchById(updateDetails);
            });
        }
    }

    /*
    * 完成采购单：
    * 1、改变采购单状态
    * 2、改变采购单中的采购项的状态
    * 3、将成功采购的进行入库
    * */
    @Transactional
    @Override
    public void done(PurchaseFinishVo finishVo) {
        //改变采购单的状态,采购单的状态要根据旗下的采购项的状态进行变化
        //如果所有的采购项的状态都是已完成，那么采购单的状态就是完成，
        //如果有一个采购项的状态是失败的，那么采购单的状态就是有异常
        //获取采购单id
         Long id = finishVo.getId();
         Boolean flag=true;
        //获取采购项
        List<PurchaseItemDoneVo> items = finishVo.getItems();
        List<PurchaseDetailEntity> updateItems=new ArrayList<>();
        for (PurchaseItemDoneVo item: items
             ) {
            PurchaseDetailEntity detailEntity=new PurchaseDetailEntity();
            if(item.getStatus()==WareConstant.PurchaseDetailEnum.HASERROR.getCode())
            {
                flag=false;
                detailEntity.setStatus(item.getStatus());

            }
            else {
                detailEntity.setStatus(WareConstant.PurchaseDetailEnum.FINISH.getCode());
                //采购项采购成功，那么要对这些采购成功的商品进行入库
                PurchaseDetailEntity detailInfo=detailService.getById(item.getItemId());

                wareSkuService.addStock(detailInfo.getSkuId(),detailInfo.getWareId(),detailInfo.
                        getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            updateItems.add(detailEntity);
        }
        detailService.updateBatchById(updateItems);
        PurchaseEntity updatePurchase = new PurchaseEntity();
        updatePurchase.setId(id);
        //改变采购单的状态
        updatePurchase.setStatus(flag?WareConstant.PurchaseEnum.FINISH.getCode():
                WareConstant.PurchaseEnum.HASERROR.getCode());
        updatePurchase.setUpdateTime(new Date());
        this.updateById(updatePurchase);

    }


}